<!-- 分配弹出框 -->
<template>
  
  <el-dialog :model-value="props.dialogTableVisible" title="分配宿舍" width="800" @close="headlerClose">
    <el-text class="mx-1">需求人数: {{ props.selectedClassData.classPeople }} / {{ selectRoomCount }}</el-text>
    <div class="tree">
      <el-tree
    style="max-width: 600px"
    :data="props.Unallocated"
    show-checkbox
    @check-change="checkChange"
    :props="{
      disabled: 'children',
    }"
  />
    </div>
  <el-button type="primary" @click="submit">分配</el-button>
  </el-dialog>
</template>

<script setup>
import { ref } from "vue";
import {distributionRoom} from "@/api/class.js"
const props = defineProps({
    dialogTableVisible:{
        type: Boolean,
        default: false
    },
    Unallocated:{
        type: Array,
        default: () => []
    },
    selectedClassData:{
      type:Object,
      default: ()=>({})
    }
})
const selectRoomCount = ref(0);
const selectRoomIdArr = ref([])
// 选择宿舍
const checkChange = (data,value1,value2) =>{
  if(!data.children){
    if(value1){
      selectRoomCount.value += +data.roomCapacity
      selectRoomIdArr.value.push(data.id)
    }else{
      selectRoomCount.value -= data.roomCapacity
      const index = selectRoomIdArr.value.indexOf(data.id);
      selectRoomIdArr.value.splice(index,1);
    }
  }
}


// 关闭弹窗
const emit = defineEmits(["headlerClose"])
const headlerClose = () =>{
    emit("headlerClose")
}
// 分配
const submit = async () => {
  if(selectRoomCount.value < props.selectedClassData.classPeople){
    ElMessage.error('需要的宿舍不够')
    return
  }
  if(selectRoomCount.value  > +props.selectedClassData.classPeople + 10){
    ElMessage.error('多余的床位不能多余10张')
    return
  }
  const {data} = await distributionRoom(selectRoomIdArr.value,props.selectedClassData.id)
  if(data){
    headlerClose()
    ElMessage({
    message: data,
    type: 'success',
  })
  }
  
}
</script>

<style lang="less" scoped>
.tree{
  padding: 20px 0;
}
</style>